import 'dart:convert';
import 'dart:developer';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/LoadToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/SetPower.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/ShowToast.dart';
import 'package:schoolassets/Tools%E5%B7%A5%E5%85%B7/requestUrl.dart';
import 'package:shared_preferences/shared_preferences.dart';
/**
 * Creat For 11643
 * CreatTime 2022/8/11
 * Description:盘点详情
 */
class Inventory extends StatefulWidget {
  Inventory({Key? key,required this.planID}) : super(key: key);
  var planID;
  @override
  State<Inventory> createState() => _InventoryState();
}

class _InventoryState extends State<Inventory> {
  //原生主动向flutter发送数据通道
  static const channel = const BasicMessageChannel(
      'com.flutter.BasicMessageChannel', StandardMessageCodec());
  ///定义一个通道,flutter调用原生方法
  static const platform = const MethodChannel('com.RfidRead.rfidread');
  //是否读取中
  bool IsReading = false;
  //读取的入库列表
  List GoodsList=[];
  //手持机是否初始化成功
  var IsInit = "false";
  //盘点列表
  List Data = [];
  //盘点数据一维数组
  List OnData = [];
  TextEditingController _RFIDController = new TextEditingController();
  var InventoryXiangQing=[];
  String Token="";
  ///Widget 选择仓库组件数组
  List<PopupMenuEntry<String>> WIdgetCangKu = [];
  ///仓库数组
  var CangKuList = [];
  ///仓库选择的id
  String CangKuId="";
  ///仓库
  TextEditingController CangKuController = new TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero,() async {
      // 获取本地token
      final SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      Token = sharedPreferences.getString('Token')!;

      //获取盘点单详情
      GetInventoryXiangQing();
      //获取存放地点
      GetCangKu();
      InitRfid();
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //  销毁RFID
    DisposeRFID();
    DisScan();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("盘点详情",style: TextStyle(color: Colors.white,fontSize: 17),),
        elevation: 0,
        centerTitle: true,
        actions: [
          IconButton(onPressed: (){
            // 设置功率
            Navigator.push(context, MaterialPageRoute(builder: (context)=>SetPower(SetPowerType: "InventoryPower",)));
          }, icon: Icon(Icons.settings,color: Colors.white,))
        ],
      ),
      body: Container(
        padding: EdgeInsets.all(15),
        child: Column(
          children: [
            // Container(
            //   alignment: Alignment.topLeft,
            //   child: Text("盘点计划名称:${InventoryXiangQing['Name']}"),
            // ),
            //
            // Row(
            //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //   children: [
            //     Container(
            //       child: Text("计划盘点数量:${InventoryXiangQing['Count']}"),
            //     ),
            //     Container(
            //       child: Text("已盘点数量:${InventoryXiangQing['CountPar']}"),
            //     ),
            //
            //   ],
            // ),
            Container(
              alignment: Alignment.centerRight,
              child: Text("扫描总数:${GoodsList.length}",style: TextStyle(color: Colors.blue),),
            ),
            Divider(),
            Container(
              alignment: Alignment.topLeft,
              child: Text("扫描列表",style: TextStyle(fontSize: 17,fontWeight: FontWeight.w600),),
            ),
            Expanded(
                child:ListView.separated(
                  itemCount: Data.length,
                  itemBuilder: (context,index){
                    return ListTile(
                      title: Text("${Data[index]['Name']}",style: TextStyle(fontSize: 13),overflow: TextOverflow.ellipsis,maxLines: 2,),
                      subtitle:Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("编码：${Data[index]['RFID']}",style: TextStyle(fontSize: 10),),
                          Text("存放位置：${Data[index]['WarehouseIDName']==null?"":Data[index]['WarehouseIDName']}",style: TextStyle(fontSize: 10),),
                        ],
                      ),
                      trailing: Container(
                        width: 70,
                        child: Column(
                          children: [
                            Text(Data[index]['status']==0?"未盘点":Data[index]['status']==1?"已盘点":"盘盈",style: TextStyle(color: Data[index]['status']==0?Colors.black26:Data[index]['status']==1?Colors.green:Colors.orange),),
                            Data[index]['status']==2?SizedBox(
                              width: 70,
                              height: 25,
                              child: MaterialButton(
                                child: Text("修改",style: TextStyle(color: Colors.white,fontSize: 13),),
                                color: Colors.orange,
                                onPressed: (){
                                  //弹窗修改存放地点
                                  showAlertDialogUpdata(Data[index]['RFID'],index);
                                },
                              ),
                            ):Container()
                          ],
                        ),
                      ),
                    );
                  }, separatorBuilder: (BuildContext context, int index) {
                  return Divider();
                },) ),
            ///底部按钮
            Container(
              height: 50,
              width: MediaQuery.of(context).size.width - 30,
              child: GridView(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount:3,
                ),
                children: [
                  GestureDetector(
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.wifi,color:IsReading?Colors.red:Colors.black38),
                          Text(IsReading?"停止读取":"开始读取",style: TextStyle(fontSize: 13,color: IsReading?Colors.red:Colors.black38))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        //停止读卡
                        StopRead();
                      }else{
                        //读卡
                        ReadRfid();
                      }

                    },
                  ),
                  GestureDetector(
                    child:Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.delete,color: Colors.orange),
                          Text("清空数据",style: TextStyle(fontSize: 13,color: Colors.orange))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        ShowToast().MyToast("请先停止读卡");
                        return;
                      }
                      //  情况数据
                      showAlertDialog();
                    },
                  ),
                  GestureDetector(
                    child: Container(
                      alignment: Alignment.topCenter,
                      child:   Column(
                        children: [
                          Icon(Icons.cloud_upload,color: Colors.green),
                          Text("上传数据",style: TextStyle(fontSize: 13,color: Colors.green))
                        ],
                      ),
                    ),
                    onTap: (){
                      if(IsReading){
                        ShowToast().MyToast("请先停止读卡");
                        return;
                      }
                      //上传
                      UploadInventory();
                    },
                  )
                ],
              ),
            ),
            Container(
              height: 10,
            ),
          ],
        ),
      ),
    );
  }
  //  初始化rfid
  Future<void> InitRfid() async {
    // 加载框
    LoadToast().LoadingToast("初始化中...", context);
    var isinit = await platform.invokeMethod("InitRfid");
    //取出本地保存的功率
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    IsInit = isinit;
    if (isinit == "true") {
      print("初始化成功");
      if (await sharedPreferences.getInt("InventoryPower") != null) {
        var Power = await sharedPreferences.getInt("InventoryPower");
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', Power);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
        }
      } else {
        //  用系统给用户默认的功率10
        //  设置功率
        bool IsSet = await platform.invokeMethod('SetPower', 20);
        if (IsSet) {
          new ShowToast().MyToast("初始化成功");
          //  保存本地
          await sharedPreferences.setInt("InventoryPower", 20);
        }
      }
    } else {
      ShowToast().MyToast("初始化失败，请重新进入此页面!");
    }
    // GetLocationList();
    IniListenNative();
    OpenScan();
    print("初始化设备结果$isinit");
  }

  // 读取
  ReadRfid() async   {
    //  开始读取
    IsReading = true;
    setState(() {

    });
    platform.invokeMethod('ReadRfid');
  }
  //单次读取
  ReadRfidOne() async {
    // var data={
    //   "Offset":_Offset,
    //   "Len":_Len
    // };
    platform.invokeMethod('ReadRFIDOne');
  }
  // 停止读卡
  void StopRead()   {
    IsReading = false;
    setState(() {
    });
    platform.invokeMethod('StopReadRfid');
  }
  // 销毁rfid
  DisposeRFID()  {
    IsInit = "false";
    platform.invokeMethod('onDestroy');
  }
  //打开扫描
  OpenScan()async{
    platform.invokeMethod('InitScan');
  }
  //销毁扫描
  DisScan(){
    platform.invokeMethod('DestoryScan');

  }
  //  注册监听原生发送的数据
  IniListenNative() {
    LoadToast().CloseLoading();
    var value;
    channel.setMessageHandler((message) async {
      print("BluDemo已接受到原生主动发出的数据$message");
      value = json.decode(message.toString());
      if(value['Type']=="Scan"){
        //  扫描器发来的数据
        _RFIDController = new TextEditingController(text: value['ScanData']);
        if(!GoodsList.contains(_RFIDController.text)){
          GoodsList.add(_RFIDController.text);
          ///调用原生请求接口、
          var data = {
            "ID":_RFIDController.text,
            "Url":ApiUrl+"/api/AppAssetStock/GetModel",
            "Token":Token
          };
          platform.invokeMethod('GetRfidMessagePost',data);
        }
        setState(() {
        });
      }else if(value['Type']=="onKeyDown"){
        //  监听摁键摁下
        ReadRfid();
      }else if(value['Type']=="onKeyUp"){
        //摁键抬起
        StopRead();
      }else if(value['Type'] == "Request"){
        if(value['Data']!=""||value['Data']!=null){
          if(OnData.indexOf(value['Data']['RFIDCode'])>=0){
            Data[OnData.indexOf(value['Data']['RFIDCode'])]['status'] = 1;
            Data[OnData.indexOf(value['Data']['RFIDCode'])]['WarehouseIDName'] = value['Data']['WarehouseIDName'];
          }else{
            ///盘盈
            Data.add({"RFID":value['Data']['RFIDCode'],"status":2,"Name":value['Data']['Name'],"WarehouseIDName":value['Data']['WarehouseIDName']});
          }
        }
      }
      else{
        if(value['Epc']!=""){
          _RFIDController = new TextEditingController(text: value['Epc']);
          if(!GoodsList.contains(_RFIDController.text)){
            GoodsList.add(_RFIDController.text);
            ///调用原生请求接口、
            var data = {
              "ID":_RFIDController.text,
              "Url":ApiUrl+"/api/AppAssetStock/GetModel",
              "Token":Token
            };
            platform.invokeMethod('GetRfidMessagePost',data);
          }
          setState(() {
          });
        }
      }
    });
    setState(() {
    });
  }
  //获取盘点单详情
  GetInventoryXiangQing()async{
    var ResponseData;

    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetInventory/GetListInfo', 'post',
        {
          "AssetInventoryID":widget.planID
        }, "拉取数据中...", context, false,"application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      InventoryXiangQing=ResponseData['data'];
      for(var i=0;i<ResponseData['data'].length;i++){
        OnData.add(ResponseData['data'][i]['AssetStockRFID']);
        Data.add({"RFID":ResponseData['data'][i]['AssetStockRFID'],"status":ResponseData['data'][i]['State'],"Name":ResponseData['data'][i]['AssetStockName'],"WarehouseIDName":null});
      }
    } else {
      ShowToast().MyToast(ResponseData['msg']);
    }
    setState(() {
    });
  }
  UploadInventory() async {
    var ResponseData;
    var List=[];
    //构造上传的数据
    for(var i=0;i<InventoryXiangQing.length;i++){
      for(var j=0;j<GoodsList.length;j++){
        if(GoodsList[j]==InventoryXiangQing[i]['AssetStockRFID']){
          InventoryXiangQing[i]['State'] = 1;
        }
      }
    }
    print("上传数据列表i$InventoryXiangQing");
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetInventory/UpData', 'post',
        {
          "JosnData":json.encode(InventoryXiangQing),
          "AssetInventoryID":widget.planID
        }, "上传中...", context, true,"application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      ShowToast().MyToast('上传成功！');
      Navigator.pop(context,"reflash");
    } else {
      ShowToast().MyToast(ResponseData['message']);
    }
  }
  Clear(){
    OnData.clear();
    Data.clear();
    GoodsList.clear();
    GetInventoryXiangQing();
  }

  ///获取仓库
  GetCangKu()async{
    var ResponseData;
    WIdgetCangKu.clear();
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppWarehouse/Get', 'post', {"limit":99999}, "获取仓库中...", context, false, "application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      CangKuList = ResponseData['data'];
      for(var i=0;i<CangKuList.length;i++){
        WIdgetCangKu.add(PopupMenuItem<String>(
          value:CangKuList[i]['ID'],
          child: Text('${CangKuList[i]['Name']}'),
        ),);
      }
    } else {
    }
    setState(() {
    });
  }
  ///修改存放地点
  UpdataCangKu(mcontext,RFIDCode,EPCindex,WarehouseIDName)async{
    var ResponseData;
    WIdgetCangKu.clear();
    ResponseData = await new requestUrl().CommenRequest(
        '/api/AppAssetStock/ChangeStockWarehouse', 'post', {"WarehouseID":CangKuId,"RFIDCode":RFIDCode}, "修改地点中...", context, true, "application/x-www-form-urlencoded");
    if (ResponseData['code'] == 0) {
      ShowToast().MyToast("修改成功!");
      //更新UI上的地点
      Data[EPCindex]['WarehouseIDName'] = WarehouseIDName;
      Navigator.of(mcontext).pop();
    } else {
      ShowToast().MyToast(ResponseData['msg']);
    }
    setState(() {
    });
  }
  ///弹窗
  void showAlertDialog() {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: new Text('警告！'),
            //可滑动
            content: Text("确定要清空数据吗？"),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  Clear();
                },
              ),
              new FlatButton(
                child: new Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }
  ///弹窗修改地点
  void showAlertDialogUpdata(RFIDCode,EPCindex) {
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('编辑存放地点'),
            content: Container(
              height: 50,
              child:  //规格
              StatefulBuilder(
                  builder: (context, state) {
                    return Container(
                      padding: EdgeInsets.only(left: 15, right: 15),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            child: Text("存放地点："),
                          ),
                          Expanded(
                              child: Container(
                                child: PopupMenuButton<String>(
                                  child: TextField(
                                    enabled: false,
                                    controller: CangKuController,
                                    decoration: InputDecoration(
                                        hintText: "请选择存放地点",
                                        hintStyle: TextStyle(fontSize: 13),
                                        suffixIcon: Icon(Icons.arrow_drop_down)),
                                  ),
                                  itemBuilder: (context) {
                                    return WIdgetCangKu;
                                  },
                                  onSelected: (value) {
                                    print(value);
                                    for(var i = 0;i<CangKuList.length;i++){
                                      if(value==CangKuList[i]['ID']){
                                        ///匹配到了相同的oid，将选择的规格赋值显示
                                        CangKuController = new TextEditingController(text:CangKuList[i]['Name']);
                                        CangKuId = CangKuList[i]['ID'];
                                        print("找到了oid:$Type");
                                      }
                                    }
                                    state(() {});
                                  },
                                ),
                              )),
                        ],
                      ),
                    );}),
            ),
            actions: <Widget>[
              Container(
                height: 30,
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: TextButton(
                  child: Text("取 消",style: TextStyle(color: Colors.white,fontSize: 11)),
                  onPressed: () {
                    CangKuController.clear();
                    Navigator.of(context).pop();
                  },
                ),
              ),
              Container(
                height: 30,
                decoration: BoxDecoration(
                  color: Colors.blue,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: TextButton(
                  child: Text("确 定",style: TextStyle(color: Colors.white,fontSize: 11),),
                  onPressed: () {
                    if(CangKuController.text.isEmpty){
                      ShowToast().MyToast("请选择存放地点！");
                      return;
                    }
                     //修改地点
                    UpdataCangKu(context,RFIDCode,EPCindex,CangKuController.text);

                  },
                ),
              ),
            ],
          );
        });
  }
}

